package com.cc.wechat.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cc.wechat.entity.User;
import com.cc.wechat.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 自定义UserDetailsService实现
 * 用于加载用户信息，支持Spring Security的认证过程
 */
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserMapper userMapper;

    /**
     * 根据用户名加载用户信息
     * 在认证过程中被调用，用于获取用户详细信息
     *
     * @param username 用户名
     * @return UserDetails对象，包含用户的完整信息
     * @throws UsernameNotFoundException 如果用户未找到
     */
    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOne(
            new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
        );
                
        if (user == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
        
        return new CustomUserDetails(user);
    }
} 